package com.guys8.cemsbackend.controller;


import com.guys8.cemsbackend.DTO.*;
import com.guys8.cemsbackend.entity.*;
import com.guys8.cemsbackend.entity.Class;
import com.guys8.cemsbackend.service.impl.*;
import com.guys8.cemsbackend.utils.JWTutil.JWTUtil;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.LinkedList;
import java.util.List;

/**
 * (Class)表控制层
 *
 * @author breeze
 * @since 2022-08-25 09:50:53
 */
@RestController
@Api(tags=" Class-班级信息相关接口")
@RequestMapping("/Class")
public class ClassController {
    /**
     * 服务对象
     */
    @Autowired
    private ClassServiceImpl classService;
    @Autowired
    private ClassUserServiceImpl classUserService;
    @Autowired
    private UserServiceImpl userService;
    @Autowired
    private AccountServiceImpl accountService;
    @Autowired
    private HealthServiceImpl healthService;
    @Autowired
    private NacidServiceImpl nacidService;

    @GetMapping("/getByClassId/{classid}")
    @ApiOperation("//按classId查看班级信息返回（class）")
    public Response getInfoByUserId(@PathVariable Integer classid) {
        Class classs = classService.getById(classid);
        if(classs==null) return Response.restResult(0);
        return Response.restResult(1,classs);
    }


    @PostMapping("/teacher/makeClass/{classname}")
    @ApiOperation("教师创建班级成功返回（class）(token)")
    public Response makeaClass(@RequestHeader String schoolid, @PathVariable String classname){
        schoolid = JWTUtil.getUsername(schoolid);

        Account account = accountService.getbyschoolid(schoolid);
        if(account.getPermissions()>2)
            return Response.restResult(0);

        Class classs = classService.getbyclassname(classname);
        if(classs!=null&&classs.getAuditState()!=2)
            return Response.restResult(2);

        if(classs==null){
            classs = new Class(account.getAccountId(), classname);
            classService.save(classs);
        }
        else{
            classs.setCreatorId(account.getAccountId());
            classs.setAuditState(1);
            classService.updateById(classs);
        }

        Integer userid = userService.getbyschoolid(schoolid).getUserId();
        ClassUser teacher = new ClassUser(userid,classs.getClassId(),1);
        classUserService.save(teacher);

        List<UserInformation> users = new LinkedList<>();
        users.add(0,new UserInformation(userService.getById(teacher.getUserId())));
        ClassInformation classesIn = new ClassInformation(classs,users);

        return Response.restResult(1,classesIn);
    }

    @DeleteMapping("/teacher/deleteClass/{classname}")
    @ApiOperation("教师删除班级(token)")
    public Response deleteaClass(@RequestHeader String schoolid, @PathVariable String classname){
        schoolid = JWTUtil.getUsername(schoolid);

        Class classs = classService.getbyclassname(classname);
        if(classs == null){
            return Response.restResult(2);
        }

        int t = is_teacher(schoolid, classs.getClassId());
        if(t!=1) return Response.restResult(t);

        classs.setAuditState(2);
        classService.updateById(classs);
        classUserService.deletebyclass(classs.getClassId());
        return Response.restResult(1);
    }

    @PostMapping("/teacher/addStudent/{classname}&&{studentid}")
    @ApiOperation("教师添加学生(token)")
    public Response addaStudent(@RequestHeader String schoolid, @PathVariable String classname, @PathVariable String studentid){
        schoolid = JWTUtil.getUsername(schoolid);

        Class classs = classService.getbyclassname(classname);
        if(classs == null){
            return Response.restResult(2);
        }
        Integer classid = classs.getClassId();
        int t = is_teacher(schoolid, classid);
        if(t!=1) return Response.restResult(t);

        Integer tr_userid = userService.getbyschoolid(schoolid).getUserId();
        Integer st_userid = userService.getbyschoolid(studentid).getUserId();

        ClassUser cstudent = classUserService.getbyuser_class(st_userid, classid);
        if(!(cstudent ==null)) return Response.restResult(3);


        cstudent = new ClassUser(st_userid, classid,0);
        cstudent.audit(tr_userid,1);
        classUserService.save(cstudent);
        return Response.restResult(1);
    }

    @DeleteMapping("/teacher/deleteStudent/{classname}&&{studentid}")
    @ApiOperation("教师删除学生(token)")
    public Response deleteaStudent(@RequestHeader String schoolid, @PathVariable String classname, @PathVariable String studentid){
        schoolid = JWTUtil.getUsername(schoolid);

        Class classs = classService.getbyclassname(classname);
        if(classs == null){
            return Response.restResult(2);
        }
        Integer classid = classs.getClassId();

        int t = is_teacher(schoolid, classid);
        if(t!=1) Response.restResult(t);

        Integer tr_userid = userService.getbyschoolid(schoolid).getUserId();
        Integer st_userid = userService.getbyschoolid(studentid).getUserId();

        ClassUser cstudent = classUserService.getbyuser_class(st_userid, classid);
        if(cstudent == null) return Response.restResult(3);

        cstudent.audit(tr_userid,2);
        classUserService.updateByMultiId(cstudent);
        classUserService.deletebyuser_class(st_userid, classid);
        return Response.restResult(1);
    }

    @GetMapping("/teacher/getAllStudent/{classname}")
    @ApiOperation("//教师查看所有学生成功返回list<user>(token)")
    public Response getallStudent(@RequestHeader String schoolid, @PathVariable String classname){
        schoolid = JWTUtil.getUsername(schoolid);

        Class classs = classService.getbyclassname(classname);
        if(classs == null){
            return Response.restResult(2);
        }
        Integer classid = classs.getClassId();

        int t = is_teacher(schoolid, classid);
        if(t!=1) return Response.restResult(t);

        List<ClassUser> cstus = classUserService.getstudentinclass(classid);
        List<UserInformation> users = userService.getstudents(cstus);

        return Response.restResult(1,users);
    }

    @GetMapping("/teacher/getStudent/{classname}&&{studentid}")
    @ApiOperation("//教师查看某个学生成功返回user(token)")
    public Response getaStudent(@RequestHeader String schoolid, @PathVariable String classname, @PathVariable String studentid){
        schoolid = JWTUtil.getUsername(schoolid);

        Class classs = classService.getbyclassname(classname);
        if(classs == null){
            return Response.restResult(2);
        }
        Integer classid = classs.getClassId();

        int t = is_teacher(schoolid, classid);
        if(t!=1) return Response.restResult(t);

        Integer st_userid = userService.getbyschoolid(studentid).getUserId();
        ClassUser cstudent = classUserService.getbyuser_class(st_userid, classid);
        if(cstudent == null) return Response.restResult(3);

        return Response.restResult(1,new UserInformation(userService.getById(st_userid)));
    }

    @GetMapping("/teacher/getAllWaitStudent/{classname}")
    @ApiOperation("教师获取所有待审核加入班级学生成功返回list<user>(token)")
    public Response getallwaitStudent(@RequestHeader String schoolid,@PathVariable String  classname){
        schoolid = JWTUtil.getUsername(schoolid);

        Class classs = classService.getbyclassname(classname);
        if(classs == null){
            return Response.restResult(2);
        }
        Integer classid = classs.getClassId();

        int t = is_teacher(schoolid,classid);
        if(t!=1) return Response.restResult(t);

        List<ClassUser> cstus = classUserService.getstudentwaitinclass(classid);
        List<UserInformation> users = userService.getstudents(cstus);

        return Response.restResult(1,users);
    }

    @GetMapping("/teacher/auditStudent/{classname}&&{studentid}&&{audit}")
    @ApiOperation("教师审核学生(token)")
    public Response allowStudent(@RequestHeader String schoolid,@PathVariable String classname,@PathVariable String studentid,@PathVariable Integer audit){
        schoolid = JWTUtil.getUsername(schoolid);

        Class classs = classService.getbyclassname(classname);
        if(classs == null){
            return Response.restResult(2);
        }
        Integer classid = classs.getClassId();

        int t = is_teacher(schoolid,classid);
        if(t!=1) return Response.restResult(t);

        Integer tr_userid = userService.getbyschoolid(schoolid).getUserId();
        Integer st_userid = userService.getbyschoolid(studentid).getUserId();
        ClassUser cstudent = classUserService.getbyuser_class(st_userid,classid);
        if(cstudent == null) return Response.restResult(3);

        if(audit==1) {
            cstudent.audit(tr_userid, audit);
            classUserService.updateByMultiId(cstudent);
        }if(audit == 2){
            cstudent.audit(tr_userid, audit);
            classUserService.updateByMultiId(cstudent);
//            classUserService.deleteByMultiId(cstudent);
        }
        return Response.restResult(1);
    }

    @GetMapping("/teacher/getClasses/")
    @ApiOperation("教师获取所有班级信息列表(token)")
    public Response getClasses(@RequestHeader String schoolid){
        schoolid = JWTUtil.getUsername(schoolid);

        User teacher = userService.getbyschoolid(schoolid);
        List<ClassUser> teachers = classUserService.getClassesbyteacher(teacher.getUserId());

        List<Class_health_nacid> classes = new LinkedList<>();
        for(ClassUser classteacher:teachers){
            Class classs = classService.getById(classteacher.getClassId());
            List<ClassUser> students = classUserService.getstudentinclass(classs.getClassId());

            List<User_health_nacid> studentshn = new LinkedList<>();
            for(ClassUser classstudent : students) {
                User student = userService.getById(classstudent.getUserId());
                Nacid nacid = nacidService.getById(student.getLastNacid());
                Health health = healthService.getById(student.getLastHealthid());
                User_health_nacid userhn = new User_health_nacid(health, nacid, student);
                studentshn.add(userhn);
            }

            classes.add(new Class_health_nacid(classs,studentshn));
        }
        return Response.restResult(1,classes);
    }

    @GetMapping("/teacher/getClasses/getStudent/{schoolid}")
    @ApiOperation("教师根据学号获取学生信息")
    public Response getstudent(@PathVariable String schoolid){
        User student = userService.getbyschoolid(schoolid);
        UserInformation ustudent = new UserInformation(student);
        List<Nacid> nacids = nacidService.getallById(student.getUserId());
        List<NacidInformation> nacidss = new LinkedList<>();
        for(Nacid n:nacids){
            nacidss.add(new NacidInformation(n));
        }
        List<Health> healths = healthService.getallById(student.getUserId());
        List<HealthInformation> healthss = new LinkedList<>();
        for(Health h:healths){
            healthss.add(new HealthInformation(h));
        }
        return Response.restResult(1,ustudent,nacidss,healthss);
    }

    private Integer is_teacher(String schoolid,Integer classid){
        Integer userid = userService.getbyschoolid(schoolid).getUserId();
        ClassUser cteacher = classUserService.getbyuser_class(userid,classid);
        if(cteacher==null)return 2;
        if(cteacher.getUserType()==0) return 0;
        return 1;
    }
}

